<template>
  <div class="delivery-admin-profile">
    <el-main>
      <h1>个人信息</h1>
      <!-- 个人信息卡片 -->
      <el-card class="profile-card">
        <template #header>
          <div class="card-header">
            <h2>个人信息</h2>
            <el-button
              :type="isEditing ? 'primary' : 'default'"
              @click="isEditing ? saveUserInfo() : startEditing()"
            >
              {{ isEditing ? '保存' : '修改' }}
            </el-button>
          </div>
        </template>

        <el-form :model="userInfo" label-width="120px">
          <el-form-item label="用户名">
            <el-input v-model="userInfo.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="角色">
            <el-tag :type="getRoleType(userInfo.role)">{{ getRoleText(userInfo.role) }}</el-tag>
          </el-form-item>
          <el-form-item label="手机号码">
            <el-input v-model="userInfo.phone" :disabled="!isEditing"></el-input>
          </el-form-item>
          <el-form-item label="电子邮箱">
            <el-input v-model="userInfo.email" :disabled="!isEditing"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input type="textarea" v-model="roleDescription" disabled></el-input>
          </el-form-item>
        </el-form>
      </el-card>
    </el-main>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import axios from 'axios'
import { getToken } from '@/utils/auth'

const userStore = useUserStore()
const userInfo = ref({
  username: '',
  role: '',
  phone: '',
  email: ''
})
const roleDescription = ref('')
const isEditing = ref(false)

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    const response = await axios.get('/api/users/profile/', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    if (response.data) {
      const userData = response.data
      userInfo.value = {
        username: userData.username,
        role: userData.role,
        phone: userData.phone || '',
        email: userData.email || ''
      }
      roleDescription.value = getRoleDescription(userData.role)
    } else {
      ElMessage.error('获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败: ' + (error.response?.data?.detail || error.message))
  }
}

// 更新用户信息
const updateProfile = async (userData) => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    const response = await axios.put('/api/users/me/update/', {
      email: userData.email,
      phone: userData.phone
    }, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    if (response.data) {
      return response.data
    } else {
      throw new Error('更新用户信息失败')
    }
  } catch (error) {
    console.error('更新用户信息失败:', error)
    throw error
  }
}

// 获取角色类型样式
const getRoleType = (role) => {
  const typeMap = {
    admin: 'danger',
    purchaser: 'warning',
    salesman: 'success',
    deliveryman: 'info',
    delivery_admin: 'success',
    customer: 'primary'
  }
  return typeMap[role] || 'info'
}

// 获取角色文本
const getRoleText = (role) => {
  const textMap = {
    admin: '系统管理员',
    purchaser: '采购员',
    salesman: '销售员',
    deliveryman: '配送员',
    delivery_admin: '配送管理员',
    customer: '客户'
  }
  return textMap[role] || '未知角色'
}

// 获取角色描述
const getRoleDescription = (role) => {
  const descriptionMap = {
    admin: '系统管理员可以管理所有用户、订单、产品和配送任务，并查看系统统计数据。',
    purchaser: '采购员负责管理产品库存，处理采购订单，确保产品供应充足。',
    salesman: '销售员负责处理客户订单，管理客户关系，跟踪订单状态。',
    deliveryman: '配送员负责处理配送任务，更新配送状态，确保订单及时送达。',
    delivery_admin: '配送管理员负责管理配送任务、配送员和查看配送数据分析。',
    customer: '客户可以浏览产品，下单购买，查看订单状态。'
  }
  return descriptionMap[role] || '暂无角色描述'
}

// 开始编辑
const startEditing = () => {
  isEditing.value = true
}

// 保存用户信息
const saveUserInfo = async () => {
  try {
    await updateProfile(userInfo.value)
    ElMessage.success('个人信息保存成功')
    isEditing.value = false
    // 重新获取用户信息以更新显示
    await fetchUserInfo()
  } catch (error) {
    ElMessage.error('保存用户信息失败: ' + (error.response?.data?.detail || error.message))
  }
}

// 页面加载时获取数据
onMounted(async () => {
  try {
    await fetchUserInfo()
  } catch (error) {
    console.error('初始化数据加载失败:', error)
    ElMessage.error('数据加载失败: ' + error.message)
  }
})
</script>

<style scoped>
.delivery-admin-profile {
  height: 100%;
  width: 100%;
}

.profile-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-card .card-header h2 {
  margin: 0;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>